//user模块名，内部方法调用使用模块名，更改模块名会出错
//缓存存储病人列表数据及当前病人索引号
// {
//		userInfo: {} 用户基本信息
// }
import $http from "@/static/js/http.js"
import $api from "@/static/js/api.js"

const storeName="user_";
const storeKeys=[
	{name:"token", defVal:null },
	{name:"userInfo", defVal:{} },
	{name:"appState", defVal:{} },
	{name:"temporary", defVal:{}},
];

// initial state
const state = () => ({
	token:"",
    userInfo:{},
	appState:{},
	temporary:{},
})

// mutations
const mutations = {
	userLogout(state) {
		state.userInfo = {};
		state.token = "";
		uni.clearStorage();
	},
	userRefresh(state){
		for(let keyObj of storeKeys){
			let key = keyObj.name;
			try {
				let data = uni.getStorageSync(storeName + key);
				if(!data){//还未获取数据，退出
					state[key] = keyObj.defVal;
					// console.log(key+"无缓存数据，设置默认");
					continue
				}
				state[key] = data;
			} catch (e) {
			    console.error(key+"缓存数据刷新失败");
			}
		}
	},
	setTemporary(state, dataObj){
		Object.assign(state.temporary, dataObj)
	}
}

// actions
const actions = {
	//写入数据，格式：
	/*{
		data: {
			字段: 数据
		},
		success: 成功后执行
		fail: 失败后执行
	}*/
	setData({ commit },obj){
		if(!obj.data){
			console.log("缓存写入数据格式错误");
			return
		}
		try {
			//真实数据层外包裹一层处理函数
			for(let key of Object.keys(obj.data)){
				uni.setStorageSync(storeName + key, obj.data[key]);
			}
			commit('userRefresh');
			if(obj.success){
				obj.success();
			}
		} catch (e) {
			console.error('用户数据存储失败');
			if(obj.fail){
				obj.fail();
			}
			return Promise.reject();
		}
	},
	clearData({ commit }){
		commit('userLogout');
		uni.showToast({
		    title: '退出成功',
		    icon: 'none',
		    duration: 1500,
		});
		//返回登录页
		setTimeout(function(){
			uni.redirectTo({
				url:"/pages/login/login"
			})
		},1500);
	},
	refresh({ commit }){
		commit('userRefresh',commit);
	},
	//更改用户数据项
	changeData({ commit }, obj){
		if(!obj.data){
			console.log("缓存写入数据格式错误");
			return
		}
		try{
			let data = uni.getStorageSync(storeName + "userInfo");
			Object.assign(data, obj.data);
			uni.setStorageSync(storeName + "userInfo", data);
			commit('userRefresh',commit);
			if(obj.success){
				obj.success();
			}
		}catch{
			console.log("更改用户缓存数据失败", obj);
			if(obj.fail){
				obj.fail();
			}
			return Promise.reject();
		}
	},
	//设置临时数据
	setTemp({ commit }, obj){
		if(!obj || !$api.isObject(obj.data)){
			console.log("缓存写入数据格式错误");
			return
		}
		commit('setTemporary',obj.data);
		if(obj.success){
			obj.success();
		}
		if(obj.complete){
			obj.complete();
		}
	}
}

// getters
const getters = {}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}
